<?php
namespace app\backend\controller;

class SubscriberStatistics extends Backend {

	/**
	 * 新增用户
	 */
	public function create() {
		
		$request = \think\Request::instance();
		if(true == $request->isAjax()){
			
			$where = array();
			$condition = array();
			$condition['date_range'] = $request->post('date_range', '');
			if(0 < mb_strlen($condition['date_range'], 'utf8')){
				$date_range = explode(' ~ ', $condition['date_range']);
				if(2 === count($date_range)){
					$date_range[0] = strtotime($date_range[0]);
					$date_range[1] = strtotime($date_range[1] . ' +1 day -1 second');
					if(is_integer($date_range[0]) && is_integer($date_range[1])){
						$where['subscriber.create_time'] = array('between', $date_range);
					};
				};
			};
			
			if(!isset($where['subscriber.create_time'])){
				return $this->disposeJson(1, '关键参数不存在');
			}else if(($date_range[0] + (60 * 60 * 24 * 31)) < $date_range[1]){
				return $this->disposeJson(1, '区间不能大于31天');
			};
			
			$field = array(
				'FROM_UNIXTIME(`subscriber`.`create_time`, "%Y-%m-%d") AS `date_string`',
				'COUNT(`subscriber`.`id`) AS `number_count`',
			);
			$select_list = \app\common\model\SubscriberModel::field($field)
				->where($where)
				->group('`date_string`')->select();
			$dispose_list = $this->perfectToDate($select_list, array('number_count'), $date_range[0], $date_range[1]);
			unset($select_list, $date_range);
			
			$title_list = array();
			$value_list = array();
			foreach($dispose_list as $result){
				$title_list[] = $result['date_string'];
				$value_list[] = round($result['number_count'], 2);
			};
			unset($dispose_list);
			
			
			return $this->disposeJson(0, '', array(
				'title' => $title_list,
				'value' => $value_list,
			));
			
		}else{
			
			$view = \think\View::instance();
		
			return $view->fetch();
			
		};
	}
	
	/**
	 * 补全日期
	 * @param array $data_array 数据列表
	 * @param array $data_field 数据内容列
	 * @param integer $date_start 开始日期
	 * @param integer $date_end 结束日期
	 * @param string $format_string 格式化类型
	 */
	private function perfectToDate($data_array, $data_field, $date_start, $date_end) {
		
		// 处理空数据
		$data_null = array();
		foreach($data_field as $value){
			$data_null[$value] = 0;
		};
		// 日期列表
		$date_list = array();
		for($i = $date_start; $i <= $date_end; $i = $i + (60 * 60* 24)){
			$date_list[] = date('Y-m-d', $i);
		};
		// 处理日期列表
		$data_list = array();
		foreach($date_list as $date_string){
			
			foreach($data_array as $data){
				if($date_string === $data->date_string){
					$data_list[] = $data->toArray();
					continue 2;
				};
			};
			
			$data = array(
				'date_string' => $date_string,
			);
			$data_list[] = array_merge($data, $data_null);
		};
		return $data_list;
	}
	
}